package com.anlu.netty.chapter02.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * netty的服务器端
 */
public class EchoServer {

    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public void start() throws InterruptedException{
        final  EchoServerHandler serverHandler = new EchoServerHandler();
        /**
         * 线程组
         */
        EventLoopGroup group = new NioEventLoopGroup();
        EventLoopGroup work =new NioEventLoopGroup();
        try{
            /**
             * 服务器端启动必备
             */
            ServerBootstrap b = new ServerBootstrap();
            b.group(group,work)
             .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .childOption(ChannelOption.TCP_NODELAY,true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //在socket通道中添加處理器
                            socketChannel.pipeline().addLast(new EchoServerHandler());
                        }
                    });
            //绑定到端口，阻塞等到连接完成
            ChannelFuture f =b.bind().sync();
            //阻塞，直到channel关闭
            f.channel().closeFuture().sync();

        }finally {
            group.shutdownGracefully().sync();
        }

    }

    public static void main(String[] args) throws InterruptedException{
        int port = 9999;
        EchoServer echoServer =new EchoServer(port);
        System.out.println("服务器即将启动");
        echoServer.start();
        System.out.println("服務器关闭");
    }
}
